package com.ja.openchat.ui.chat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.blankj.utilcode.util.BarUtils;
import com.github.chrisbanes.photoview.PhotoView;
import com.gyf.immersionbar.ImmersionBar;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @author imndx
 */
public class PreviewLocalImageActivity extends JaBaseActivity {
    private SparseArray<View> views;
    private ViewPager viewPager;
    private MMPagerAdapter adapter;

    private static int currentPosition = -1;
    private static List<String> entries;
    private boolean pendingPreviewInitialMedia;

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarLightMode(this, false);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }

    private class MMPagerAdapter extends PagerAdapter {
        private List<String> entries;

        public MMPagerAdapter(List<String> entries) {
            this.entries = entries;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            View view;
            String entry = entries.get(position);
            view = LayoutInflater.from(PreviewLocalImageActivity.this).inflate(R.layout.preview_photo, null);
            view.setTag(position);
            container.addView(view);
            views.put(position % 3, view);
            if (pendingPreviewInitialMedia) {
                preview(view, entry);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            // do nothing ?
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return entries == null ? 0 : entries.size();
        }

        public String getEntry(int position) {
            return entries.get(position);
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }
    }

    final ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // TODO 可以在此控制透明度
        }

        @Override
        public void onPageSelected(int position) {
            View view = views.get(position % 3);
            if (view == null) {
                // pending layout
                return;
            }
            setCurrentTitle(position);
            String entry = adapter.getEntry(position);
            preview(view, entry);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private void preview(View view, String message) {
        PhotoView photoView = view.findViewById(R.id.photoView);
        photoView.setImageResource(getImageResource(message));
    }

    public int getImageResource(String imageName){
        int resourceId = getResources().getIdentifier(imageName, "mipmap", getPackageName());
        if(resourceId==0){
            resourceId = getResources().getIdentifier(imageName, "drawable", getPackageName());
        }
        return resourceId;
    }


    private TextView tv_bar_title;

    @Override
    public void initView() {
        super.initView();
        views = new SparseArray<>(3);
        viewPager = findViewById(R.id.viewPager);
        adapter = new MMPagerAdapter(entries);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(1);
        viewPager.addOnPageChangeListener(pageChangeListener);
        tv_bar_title = findViewById(R.id.tv_bar_title);

        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.drawable.transparent_shape);
        ((ViewGroup.MarginLayoutParams)toolbar.getLayoutParams()).topMargin = ImmersionBar.getStatusBarHeight(this);
        tv_bar_title.setTextColor(ContextCompat.getColor(this,R.color.white));
        AppCompatImageView iv_bar_back = findViewById(R.id.iv_bar_back);
        iv_bar_back.setImageResource(R.mipmap.com_nav_ic_back_white_normal);
        iv_bar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (currentPosition == 0) {
            viewPager.post(() -> {
                pageChangeListener.onPageSelected(0);
            });
            setCurrentTitle(0);
        } else {
            viewPager.setCurrentItem(currentPosition);
            pendingPreviewInitialMedia = true;
            setCurrentTitle(currentPosition);
        }
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_mm_preview;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    private void setCurrentTitle(int currentIndex){
        if(entries!=null&&entries.size()>currentIndex){
            tv_bar_title.setText(String.format("%d/%d",currentIndex+1,entries.size()));
        }else{
            tv_bar_title.setText("");
        }
    }


    public static void previewMedia(Context context, List<String> entries, int current) {
        if (entries == null || entries.isEmpty()) {
            Log.w(PreviewLocalImageActivity.class.getSimpleName(), "message is null or empty");
            return;
        }
        PreviewLocalImageActivity.entries = entries;
        PreviewLocalImageActivity.currentPosition = current;
        Intent intent = new Intent(context, PreviewLocalImageActivity.class);
        context.startActivity(intent);
    }

    public static void previewImage(Context context, String imageMessageContent) {
        List<String> entries = new ArrayList<>();
        entries.add(imageMessageContent);
        previewMedia(context, entries, 0);
    }


}
